package com.example.villagemanager.network;

import android.app.ProgressDialog;

import com.example.villagemanager.model.entity.BaseResponse;
import com.example.villagemanager.ui.widget.ToastTool;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    private ProgressDialog mDialog;

    public BaseObserver(){}

    public BaseObserver(ProgressDialog dialog) {
        mDialog = dialog;
        mDialog.show();
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseResponse<T> response) {
        dismissDialog();
        if(response == null){
            error("服务器异常");
            return;
        }
        if(response.isSuccess()){
            onSuccess(response);
        } else {
            error(response.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        dismissDialog();
        error("网络异常");
        e.printStackTrace();
    }

    @Override
    public void onComplete() {
        dismissDialog();
    }

    private void dismissDialog(){
        if(mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }

    public abstract void onSuccess(BaseResponse<T> response);

    public void error(String msg){
        ToastTool.show(msg);
    }
}
